#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/kdev_t.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/slab.h>
#include <linux/uaccess.h>

MODULE_LICENSE("GPL");

struct scull_dev {
	int quantum;              /* the current quantum size */
	int qset;                 /* the current array size */
	unsigned long size;       /* amount of data stored here */
	unsigned int access_key;  /* used by sculluid and scullpriv */
	struct semaphore sem;     /* mutual exclusion semaphore     */
	struct cdev cdev;	  /* Char device structure		*/
    char *buffer;
    unsigned long buffer_size;
};

struct scull_dev *scull_devices;	/* allocated in scull_init_module */
int scull_major =   0;
int scull_minor =   0;
int scull_nr_devs = 4;	/* number of bare scull devices */
int scull_quantum = 4000;
int scull_qset =    1000;

static void __exit hello_exit(void)
{
	int i;
	dev_t devno = MKDEV(scull_major, scull_minor);
	/* Get rid of our char dev entries */
	if (scull_devices) {
		for (i = 0; i < scull_nr_devs; i++) {
			cdev_del(&scull_devices[i].cdev);
            if (scull_devices[i].buffer) {
                kfree(scull_devices[i].buffer);
                scull_devices[i].buffer = NULL; 
                scull_devices[i].buffer_size = 0; 
            }
		}
		kfree(scull_devices);
	}

	/* cleanup_module is never called if registering failed */
	unregister_chrdev_region(devno, scull_nr_devs);
    printk(KERN_DEBUG "goodbye world.\n");
}
/*
 * The "extended" operations -- only seek
 */

loff_t scull_llseek(struct file *filp, loff_t off, int whence)
{
	struct scull_dev *dev = filp->private_data;
	loff_t newpos;

	switch(whence) {
	  case 0: /* SEEK_SET */
		newpos = off;
		break;

	  case 1: /* SEEK_CUR */
		newpos = filp->f_pos + off;
		break;

	  case 2: /* SEEK_END */
		newpos = dev->size + off;
		break;

	  default: /* can't happen */
		return -EINVAL;
	}
	if (newpos < 0) return -EINVAL;
	filp->f_pos = newpos;
	return newpos;
}
/*
 * Open and close
 */

int scull_open(struct inode *inode, struct file *filp)
{
	struct scull_dev *dev; /* device information */

	dev = container_of(inode->i_cdev, struct scull_dev, cdev);
	filp->private_data = dev; /* for other methods */

	/* now trim to 0 the length of the device if open was write-only */
	if ( (filp->f_flags & O_ACCMODE) == O_WRONLY) {
		if (down_interruptible(&dev->sem))
			return -ERESTARTSYS;
		// scull_trim(dev); /* ignore errors */
		up(&dev->sem);
	}
	return 0;          /* success */
}
/*
 * Data management: read and write
 */
ssize_t scull_read(struct file *filp, char __user *buf, size_t count,
                loff_t *f_pos)
{
	struct scull_dev *dev = filp->private_data; 
	ssize_t retval = 0;

	if (down_interruptible(&dev->sem))
		return -ERESTARTSYS;
	if (*f_pos >= dev->buffer_size)
		goto out;
	if (*f_pos + count > dev->buffer_size)
		count = dev->buffer_size - *f_pos;

	if (copy_to_user (buf, dev->buffer, count)) {
		retval = -EFAULT;
		goto out;
	}
	up (&dev->sem);

	*f_pos += count;
	return count;
out:
	up(&dev->sem);
	return retval;
}

ssize_t scull_write(struct file *filp, const char __user *buf, size_t count,
                loff_t *f_pos)
{
	struct scull_dev *dev = filp->private_data;
	ssize_t retval = -ENOMEM; /* value used in "goto out" statements */

	if (down_interruptible(&dev->sem))
		return -ERESTARTSYS;

    if (dev->buffer_size + count >= scull_quantum) {
        dev->buffer_size = 0;
    }
	if (copy_from_user (dev->buffer + dev->buffer_size, buf, count)) {
		retval = -EFAULT;
		goto nomem;
	}
    dev->buffer_size += count;
    dev->buffer[dev->buffer_size] = '\0';
    printk(KERN_WARNING "scull:write %d %s\n", scull_major, dev->buffer);
	*f_pos += count;
    retval = count;

        /* update the size */
	if (dev->size < *f_pos)
		dev->size = *f_pos;

out:
	up(&dev->sem);
	return retval;
nomem:
	up (&dev->sem);
	return retval;
}

/*
 * The ioctl() implementation
 */

long scull_ioctl(struct file *filp,
                 unsigned int cmd, unsigned long arg)
{

	int err = 0, tmp;
	int retval = 0;
    return retval;
}

int scull_release(struct inode *inode, struct file *filp)
{
	return 0;
}

struct file_operations scull_fops = {
	.owner =    THIS_MODULE,
	.llseek =   scull_llseek,
	.read =     scull_read,
	.write =    scull_write,
	.unlocked_ioctl =    scull_ioctl,
	.open =     scull_open,
	.release =  scull_release,
};


/*
 * Set up the char_dev structure for this device.
 */
static void scull_setup_cdev(struct scull_dev *dev, int index)
{
	int err, devno = MKDEV(scull_major, scull_minor + index);
    
	cdev_init(&dev->cdev, &scull_fops);
	dev->cdev.owner = THIS_MODULE;
	dev->cdev.ops = &scull_fops;
	err = cdev_add (&dev->cdev, devno, 1);
	/* Fail gracefully if need be */
	if (err)
		printk(KERN_NOTICE "Error %d adding scull%d", err, index);
}


static int __init hello_init(void)
{
	int result, i;
	dev_t dev = 0;
    result = alloc_chrdev_region(&dev, scull_minor, scull_nr_devs,
            "scull");
    scull_major = MAJOR(dev);
	if (result < 0) {
		printk(KERN_WARNING "scull: can't get major %d\n", scull_major);
		return result;
	}
	scull_devices = kmalloc(scull_nr_devs * sizeof(struct scull_dev), GFP_KERNEL);
	if (!scull_devices) {
		result = -ENOMEM;
		goto fail;  /* Make this more graceful */
	}
	memset(scull_devices, 0, scull_nr_devs * sizeof(struct scull_dev));
    /* Initialize each device. */
	for (i = 0; i < scull_nr_devs; i++) {
		scull_devices[i].quantum = scull_quantum;
		scull_devices[i].qset = scull_qset;
        scull_devices[i].buffer = kmalloc(scull_quantum * sizeof(char), GFP_KERNEL);
        scull_devices[i].buffer_size = 0;
        if (!scull_devices[i].buffer) {
            result = -ENOMEM;
            goto fail;
        }
        sema_init(&scull_devices[i].sem, 1);
		scull_setup_cdev(&scull_devices[i], i);
	}

	dev = MKDEV(scull_major, scull_minor + scull_nr_devs);

    printk(KERN_DEBUG "hello world.\n");
    return 0;

fail:
	hello_exit();
	return result;
}

module_init(hello_init);
module_exit(hello_exit);